<script
  lang="ts"
  setup
>
import dayjs from '#build/dayjs.imports.mjs'
import fyjk from '~~/public/img/fyjk.png'
import ggaq from '~~/public/img/ggaq.png'
import ggws from '~~/public/img/ggws.png'
import jbcs from '~~/public/img/jbcs.png'
import jksy from '~~/public/img/jksy.png'
import mbfz from '~~/public/img/mbfz.png'
import xljk from '~~/public/img/xljk.png'
import zyys from '~~/public/img/zyys.png'
import { getAreaList, getCategoryList, getHealthKL, getOrgList } from '~/api/home'

const cateData = ref([])
const areaData = ref([])
const orgData = ref([])
const title = ref('志鉴分类')
const routePath = [{ name: '首页', path: '/' }, { name: title }]
const timeNow = ref('')
const selectedType = ref('1')
const valuedate = ref()
const total = ref(0)
const currentselectId = ref('')// 记录选中ID
const infoType = ref('')
const selectedIdYes = ref('border-bottom:2px solid #AC8358;color:#AC8358')
const selectedIdNo = ref('border-bottom:none;color:#5a5a5a')
const queryParams = reactive<{

  page: {
    rownumber: number
    pageNo: number
  }
  condition?: any[]
  positions?: string
}>(
  {
    page: {
      rownumber: 10,
      pageNo: 1,
    },

    positions: '首页',
  },

)

function changeSelect(data: string) {
  if (selectedType.value === '1') {
    currentselectId.value = data.split('/')[1] as string
  }
  else {
    currentselectId.value = data
  }

  console.log(data)

  if (queryParams.condition) {
    switch (selectedType.value) {
      case '1':
        queryParams.condition = queryParams.condition.filter((item) => {
          return item.colName !== 'classify_name'
        })
        queryParams.condition.push({
          colName: 'classify_name',
          ruleType: 'eq',
          value: `健康知识/${data}`,
        })

        break
      case '2':
        queryParams.condition = queryParams.condition.filter((item) => {
          return item.colName !== 'area_name'
        })
        queryParams.condition.push({
          colName: 'area_name',
          ruleType: 'eq',
          value: data,
        })

        break
      case '3':
        queryParams.condition = queryParams.condition.filter((item) => {
          return item.colName !== 'organ_name'
        })
        queryParams.condition.push({
          colName: 'organ_name',
          ruleType: 'eq',
          value: data,
        })
        break
    }
  }
  else {
    switch (selectedType.value) {
      case '1':
        queryParams.condition = [
          {
            colName: 'classify_name',
            ruleType: 'eq',
            value: `健康知识/${data}`,
          },
        ]

        break
      case '2':
        queryParams.condition = [
          {
            colName: 'area_name',
            ruleType: 'eq',
            value: data,
          },
        ]

        break
      case '3':
        queryParams.condition = [
          {
            colName: 'organ_name',
            ruleType: 'eq',
            value: data,
          },
        ]
        break
    }
  }
  getListData()
  console.log('queryParams22', queryParams)

  getSiderList(queryParams)
}
const timeYS = ref('background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,#AC8358 89.45%);color:#fff')
const timeNo = ref('background:none;color:#333;border:1px solid rgba(229,229,234,1);')
const selectedYes = ref('border-bottom:3px solid rgba(229,229,234,1)')

const listArrary = ref<object[]>([])

function clickType(item: string) {
  selectedType.value = item
  queryParams.condition = queryParams.condition?.filter(item => item.colName === 'release_time')
}
// 分页参数更改
function onPageChange(params: { pageNum: number, pageSize: number }) {
  queryParams.page.pageNo = params.pageNum
  //   queryParams.page.rownumber = 10
  getListData()
}
function extractTextFromPTags(htmlString: string) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const pTags = doc.getElementsByTagName('p')
  let text = ''
  for (let i = 0; i < pTags.length; i++) {
    text += pTags[i]?.textContent
  }
  return text
}
const router = useRouter()
const route = useRoute()

function toDetail(item: any) {
  console.log('item', item)
  router.push({ path: `/peopleHealth/knowledgeDetail/${item.Id}&1` })
}
function toDetail2(id: any) {
  router.push({ path: `/peopleHealth/knowledgeDetail/${id}&1` })
}

// 时间参数处理

function clickTime(item: string) {
  timeNow.value = item
  const res = getTimePeriod(item)
  if (res?.start && res?.end) {
    valuedate.value = [res.start, res.end]
    if (queryParams.condition) {
      queryParams.condition = queryParams.condition.filter(item => item.colName !== 'release_time')

      queryParams.condition.push({
        colName: 'release_time',
        value: valuedate.value?.length ? valuedate.value[1] : null,
        ruleType: 'le',
      })
      queryParams.condition.push({
        colName: 'release_time',
        value: valuedate.value?.length ? valuedate.value[0] : null,
        ruleType: 'ge',
      })
    }
    else {
      queryParams.condition = []
      queryParams.condition.push({
        colName: 'release_time',
        value: valuedate.value?.length ? valuedate.value[1] : null,
        ruleType: 'le',
      })
      queryParams.condition.push({
        colName: 'release_time',
        value: valuedate.value?.length ? valuedate.value[0] : null,
        ruleType: 'ge',
      })
    }

    getListData()
  }
  else {
    queryParams.condition = queryParams.condition?.filter(item => item.colName !== 'release_time')
    getListData()
  }
}
function getTimePeriod(periodType: string | undefined) {
  if (periodType) {
    const currentDate = new Date()

    switch (periodType) {
      case '1':
        const oneWeekAgo = new Date(currentDate)
        oneWeekAgo.setDate(currentDate.getDate() - 7)
        return { start: oneWeekAgo, end: currentDate }
      case '2':
        const oneMonthAgo = new Date(currentDate)
        oneMonthAgo.setMonth(currentDate.getMonth() - 1)
        return { start: oneMonthAgo, end: currentDate }
      case '3':
        const sixMonthsAgo = new Date(currentDate)
        sixMonthsAgo.setMonth(currentDate.getMonth() - 6)
        return { start: sixMonthsAgo, end: currentDate }
      case '4':
        if (valuedate.value)
          return { start: valuedate.value[0], end: valuedate.value[1] }
        else return { start: '', end: '' }
      default:
        throw new Error('Invalid period type. Choose from "week", "month", or "sixMonths"')
    }
  }
}
async function getListData() {
  try {
    const res = await getHealthKL(queryParams)
    total.value = res.page.total
    listArrary.value = []
    res.data.forEach((element) => {
      listArrary.value.push({
        title: element.key_work,
        blurd: extractTextFromPTags(element.contents),
        info: element.origin || element.publisher,
        time: dayjs(element.release_time).format('YYYY-MM-DD'),
        url: getImgUrl(element.cover_file_name),
        Id: element.id,
      })
    })
  }
  catch (error) {

  }
}
async function getTypeList() {
  const res = await getCategoryList({
    condition: [{
      colName: 'path_name',
      ruleType: 'like',
      value: '健康知识',
    }],
  })
  cateData.value = res.data[0].children
  console.log('cateData.value', cateData.value)

  const res2 = await getAreaList({
    page: {
      rownumber: 50,
      pageNo: 1,
    },
  })
  areaData.value = res2.data.slice(0, res2.data.length - 1)
  const res3 = await getOrgList({
    page: {
      rownumber: 100,
      pageNo: 1,
    },
    condition: [{
      colName: 'dependency',
      ruleType: 'eq',
      value: '市级',
    }],
  })
  orgData.value = res3.data
  console.log('res222', res, res2, res3)
}
const siderData = ref<any[]>([])
async function getSiderList(selctparam: any) {
  console.log('selctparam', selctparam)

  let res
  console.log('queryParams', queryParams)
  if (selctparam) {
    const newObj = JSON.parse(JSON.stringify(selctparam))
    newObj.condition.push({
      colName: 'column_recommendation',
      ruleType: 'eq',
      value: '是',
    })
    newObj.page = {
      rownumber: 3,
      pageNo: 1,
    }

    newObj.order = [{

      colName: 'release_time',
      orderType: 'desc', // asc升序 desc降序

    }]
    res = await getHealthKL(newObj)
  }
  else {
    res = await getHealthKL({ ...selctparam, page: {
      rownumber: 3,
      pageNo: 1,
    } })
  }
  console.log('res555', res)

  siderData.value = res.data
}
function getIcon(name1: any) {
  switch (name1) {
    case '健康素养':
      return jksy
    case '公共卫生':
      return ggws
    case '疾病常识':
      return jbcs
    case '妇幼保健':
      return fyjk
    case '慢病防治':
      return mbfz
    case '心理健康':
      return xljk
    case '中医养生':
      return zyys
    case '公共安全':
      return ggaq
    default:
      break
  }
}
function initdata() {
  getTypeList()
  // getListData()
  getSiderList(null)
  if (route.query.type && route.query.type.length) {
    selectedType.value = '1'
    changeSelect(route.query.type as string)
  }
  else {
    getListData()
  }
}
onMounted(() => {
  console.log(8888)
  initdata()
})
</script>

<template>
  <div>
    <PublicSearch type="志鉴分类" />
    <PublicSearchDialog type="志鉴分类" />
    <div class="px-40">
      <div class="bg-#fff">
        <CommonPageContainer :title="title" :path="routePath">
          <div class="mt-20px flex flex-row">
            <div class="mr-20px flex-1">
              <div v-if="infoType === '政策解读'" class="w-85%">
                <!-- <PublicList></PublicList>
                                <PublicPagination :page-size="queryParams.page.pageNo" :page-num="queryParams.page.rownumber" :total="total"
                                    @change="onPageChange" /> -->
              </div>

              <div class="h-40px flex">
                <div
                  class="cursor-pointer rounded-sm px-8px pt-6px" :style="timeNow === '1' ? timeYS : timeNo"
                  @click="clickTime('1')"
                >
                  近一周
                </div>
                <div
                  class="mx-10px cursor-pointer rounded-sm px-8px pt-6px" :style="timeNow === '2' ? timeYS : timeNo"
                  @click="clickTime('2')"
                >
                  近一月
                </div>
                <div
                  class="cursor-pointer rounded-sm px-8px pt-6px" :style="timeNow === '3' ? timeYS : timeNo"
                  @click="clickTime('3')"
                >
                  近半年
                </div>
                <div class="ml-10px">
                  <el-date-picker
                    v-model="valuedate" style="height:100%" type="daterange" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" size="large" @change="clickTime('4')"
                  />
                </div>
              </div>
              <div class="">
                <div v-if="listArrary.length">
                  <PublicList2 :list="listArrary" @click-item="toDetail" />
                </div>
                <div v-else>
                  <el-empty :image-size="200" />
                </div>
                <PublicPagination
                  :page-size="queryParams.page.rownumber" :page-num="queryParams.page.pageNo"
                  :total="total" @change="onPageChange"
                />
              </div>
            </div>

            <div class="max-w-200px min-w-175px">
              <div>
                <div
                  class="h-42px flex items-center rounded-[10px_10px_0_0] bg-[linear-gradient(159.97deg,_rgba(206,234,158,1)_-140.78%,#AC8358_89.45%)] line-height-27px"
                >
                  <div
                    class="ml-12px cursor-pointer rounded-sm p-4px" text="#fff 16px"
                    :style="selectedType === '1' ? selectedYes : ''" @click="clickType('1')"
                  >
                    类别
                  </div>
                  <div
                    class="ml-9px cursor-pointer rounded-sm p-4px" text="#fff 16px"
                    :style="selectedType === '2' ? selectedYes : ''" @click="clickType('2')"
                  >
                    属地
                  </div>

                  <div
                    class="ml-9px cursor-pointer rounded-sm p-4px" text="#fff 16px"
                    :style="selectedType === '3' ? selectedYes : ''" @click="clickType('3')"
                  >
                    机构
                  </div>
                </div>

                <div class="rounded-bl rounded-br px-20px py-15px" border="2px solid #AC8358">

                  <div v-for="item in cateData" v-if="selectedType === '1'" :key="item.id">
                    <div>
                      <div class="flex" style="align-items: center;">
                        <img :src="getIcon(item.classify_name)" alt="" style="margin-right: 10px;flex-shrink: 0;">
                        <span text="#424242 16px"> {{ item.classify_name }}</span>
                      </div>

                      <div
                        v-if="item.children.length"
                        style="display: flex;align-items: center;flex-wrap: wrap;padding:9px 0 ;"
                      >
                        <div
                          v-for="e in item.children.slice(0, item.children.length - 1)"
                          class="mr-32px h-30px cursor-pointer lh-30px"
                          @click="changeSelect(`${item.classify_name}/${e.classify_name}`)"
                        >
                          <span
                            class="itemTitle"
                            :style="currentselectId === e.classify_name ? selectedIdYes : selectedIdNo"
                            text="#5A5a5a 14px"
                          >{{ e.classify_name }}</span>
                        </div>
                      </div>
                    </div>
                    
                  </div>

                  <div v-if="selectedType === '2'">
                    <div style="display: flex;align-items: center;flex-wrap: wrap;padding:9px 0 ;">
                      <div
                        v-for="e in selectedType === '2' ? areaData : orgData "
                        class="mr-32px h-30px cursor-pointer lh-30px" @click="changeSelect(e.area_name)"
                      >
                        <span
                          class="itemTitle" :style="currentselectId === e.area_name ? selectedIdYes : selectedIdNo"
                          text="#5A5a5a 14px"
                        >{{ e.area_name }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="selectedType === '3'">
                    <div style="display: flex;align-items: center;flex-wrap: wrap;padding:9px 0 ;">
                      <div
                        v-for="e in selectedType === '2' ? areaData : orgData "
                        class="mr-32px h-30px cursor-pointer lh-30px" @click="changeSelect(e.organ_name)"
                      >
                        <span
                          class="itemTitle" :style="currentselectId === e.organ_name ? selectedIdYes : selectedIdNo"
                          text="#5A5a5a 14px"
                        >{{ e.organ_name }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div
                  class="mt-20px h-40px flex items-center rounded-tl rounded-tr px-10px py-5px"

                  bg="[linear-gradient(159.97deg,_rgba(206,234,158,1)_-140.78%,#AC8358_89.45%)]"
                >
                  <img src="/img/tj.png" alt="">
                  <div class="pl-15px" text="#fff 16px">
                    推荐
                  </div>
                </div>
                <div
                  v-if="siderData && siderData.length" class="rounded-bl rounded-br px-10px py-5px"
                  border="2px solid #AC8358"
                >
                  <div v-for="item in siderData" :key="item.id" class="cursor-pointer" @click="toDetail2(item.id)">
                    <div class="h-124px w-100%">
                      <img
                        :src="getImgUrl(item.cover_file_name)" alt=""
                        style="width: 100%;height:100%;object-fit: cover;"
                      >
                    </div>

                    <div class="itemTitledata py-10px" text="14px">
                      {{ item.title_name }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </CommonPageContainer>
      </div>
    </div>
  </div>
</template>

<style
  lang="scss"
  scoped
>
.itemTitle {
  &:hover {
    background-color: #caefe6;
    border-radius: 2px;
  }
}

.itemTitledata {
  &:hover {
    color: #AC8358;
  }
}
</style>
